//
//  RHCountryRegionVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/31.
//

#import "RHCountryRegionVC.h"
#import "RHGolbalRegionModel.h"
#import "RHGolbalServerModel.h"
#import "RHNavigationController.h"
#import "RHLoginViewController.h"
#import "RHDevRegionModel.h"
#import "RHMQTTServerInfoModel.h"
#import "NetworkConfig.h"
#import "RHTools.h"
#import "EnvironmentManage.h"


@interface RHCountryRegionVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property(nonatomic,strong)NSArray *dataArray;

@property (nonatomic ,strong) RHGolbalRegionModel *regionModel;

@property (nonatomic ,strong) RHGolbalServerModel *serverModel;
@end

@implementation RHCountryRegionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"区域选择".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self getCountryList];
    [self setupUI];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark -------- 获取国家列表 -----
-(void)getCountryList
{
    //G_getCountries   H_countryRegionCode
    [QMUITips showLoadingInView:self.view];
    
    [RHGolbalServerModel startWithBaseUrl:[EnvironmentManage sharedEnvirManage].getBaseAPIUrl APIKey:G_getServerList argument:@{} requestMethod:RequestMethodPOST requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            self.dataArray = resultModel.data;
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
        
        
//    [RHGolbalRegionModel startGetWithCompletionAPIKey:G_getServerList argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//            if(resultModel.code == 200){
//                self.dataArray = resultModel.data;
//                [self.tableView reloadData];
//            }
//    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        
//    }];

}

-(void)setupUI{
    QMUIButton *sureBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sureBtn.frame = CGRectMake(0, 0, 50, 40);
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithCustomView:sureBtn];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    [sureBtn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *tipsLab = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 200, 10)];
    tipsLab.font = [UIFont systemFontOfSize:16];
    tipsLab.text = @"请选择一个地区".rh_localized;
    [self.view addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(15);
            make.top.equalTo(self.view).offset(15);
    }];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [_tableView setSeparatorColor:kRGB(240, 240, 240) ];
    _tableView.estimatedRowHeight = 500;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.layer.cornerRadius = 8;
    _tableView.layer.masksToBounds = YES;
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(tipsLab.mas_bottom).offset(15);
        make.bottom.mas_offset(-(kSafe_bottom+20));
    }];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getCountryList];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"region"];
    if(cell==nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"region"];
    }
    
    RHGolbalServerModel *model = self.dataArray[indexPath.row];
//    cell.textLabel.text = [RHTools getAreaNameWithAreaCode:model.areaCode];;
    cell.textLabel.text = model.areaName;
    cell.textLabel.textColor = kCOLOR_HEX(@"3F4443");
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    
    
    if([model.areaCode isEqualToString:[NetworkConfig sharedConfig].areaCode])
    {
        UIImageView *rightImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        rightImg.image = [UIImage imageNamed:@"submit_success"];
        cell.accessoryView = rightImg;
    }else{
        cell.accessoryView = nil;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RHGolbalServerModel *model = self.dataArray[indexPath.row];
    for (UITableViewCell *cell in tableView.visibleCells) {
        cell.accessoryView = nil;
    }
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIImageView *rightImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    rightImg.image = [UIImage imageNamed:@"submit_success"];
    cell.accessoryView = rightImg;
    self.serverModel = model;
}

-(void)sureAction
{
    if(self.serverModel==nil){
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    [NetworkConfig sharedConfig].baseUrl = self.serverModel.apiAddress;
    [NetworkConfig sharedConfig].areaCode = self.serverModel.areaCode;
    
    //切换后获取一下个人信息
    kWeakSelf;
    [QMUITips showLoadingInView:self.view];
    [RHUserModel startGetWithCompletionAPIKey:H_accountInfo argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            RHUserModel *user = (RHUserModel*)resultModel.data;
            [PrivateMange share].currentUser = user;
            [QMUITips showSucceed:@"切换成功".rh_localized];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter]postNotificationName:SwitchRegionSuccessNotification object:nil];
                if(self.regionUpdateBlock){
                    self.regionUpdateBlock(self.serverModel.areaCode);
                }
            });
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
        

    
    
    
    /*
    //根据国家编码获取对应的服务器地址
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"countryCode":self.regionModel.countryCode,
                           @"brandId":[NetworkConfig sharedConfig].brandID
    };
    [RHGolbalServerModel startGetWithCompletionAPIKey:G_switchserverInfo argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        if(resultModel.code == 200){
            self.serverModel = resultModel.data;
            //如果选择的服务器跟当前的服务器一样
            if([self.serverModel.apiAddress isEqualToString:[NetworkConfig sharedConfig].baseUrl]){
                [NetworkConfig sharedConfig].baseUrl = self.serverModel.apiAddress;
                [UserDefaults setObject:self.regionModel.countryName forKey:kCountry];
                [UserDefaults setObject:self.regionModel.countryCode forKey:kRegionCode];
                if(self.regionUpdateBlock){
                    self.regionUpdateBlock(self.regionModel.countryName);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeBrandMerchants){
                    //切到对应国家的服务器
                    [NetworkConfig sharedConfig].baseUrl = self.serverModel.apiAddress;
             
                   
                    if(self.regionUpdateBlock){
                        self.regionUpdateBlock([RHTools getRegionNameWithCode:self.regionModel.countryCode]);
                    }
                    [QMUITips showSucceed:@"切换成功".rh_localized];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                        [[NSNotificationCenter defaultCenter]postNotificationName:SwitchRegionSuccessNotification object:nil];
                    });
                    
                }else{
                    RHNavigationController *nav = [[RHNavigationController alloc]initWithRootViewController:[[RHLoginViewController alloc]init]];
                    nav.modalPresentationStyle = UIModalPresentationFullScreen;
                    [self presentViewController:nav animated:YES completion:nil];
                }
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
     
     */
}
@end
